package com.thz.websqlit.common.util;

import java.io.*;
import java.util.UUID;

public final class FileUtil {
    /**
     * 如果目录不存在，建立目录
     * @param fileName
     */
    public static String mkdirNoExit(String fileName){
        File file = new File(fileName);
        if(!file.exists()){
            file.mkdirs();
        }
        return  file.getAbsolutePath();
    }

    public static String getUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    public static int copyStream(OutputStream outputStream,InputStream inputStream) throws IOException {
        int fileSize = 0;
        byte[] block = new byte[1024];
        int length = 0;
        while ((length = inputStream.read(block)) > 0){
            fileSize += length;
            outputStream.write(block,0,length);
            outputStream.flush();
        }
        return fileSize;
    }

    public static int saveFile(String fileName, InputStream inputStream) {
        int fileSize = 0;
        try(
            FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        ) {
            fileSize = copyStream(fileOutputStream,inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileSize;
    }
}
